package com.weimob.mcloud.wechatwork.customer.externalDependencyProxy.usermanagement;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.weimob.mcloud.wechatwork.core.base.MultiResponse;
import com.weimob.mcloud.wechatwork.core.entity.privatesphere.PrivateSphere;
import com.weimob.mcloud.wechatwork.core.entity.relation.employee.Employee;
import com.weimob.mcloud.wechatwork.core.entity.relation.group.CustomerGroupMember;
import com.weimob.mcloud.wechatwork.core.enums.group.GroupMemberTypeEnum;
import com.weimob.mcloud.wechatwork.core.service.employee.EmployeeService;
import com.weimob.mcloud.wechatwork.core.service.employee.request.SingleEmployeeAttachRequest;
import com.weimob.soa.common.utils.SoaUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 员工相关接口
 *
 * @Author LeoLee
 * @Date 2022/8/23 10:45
 * @Version 1.0
 */
@Slf4j
@Component
public class EmployeeProxy {

    @Reference
    private EmployeeService employeeService;

    @Autowired
    @Qualifier("commonThreadPool")
    private ThreadPoolTaskExecutor commonThreadPool;

    @Value("${employee.query.max.size:100}")
    Integer partitionSize;


    /**
     * 此为数据隔离用途，多bosid体系下不考虑改动
     * 分页查询某个私域下所有员工的信息（信息中包含该员工的当前vid以及他上级vid）
     *
     * @param privateSphere
     * @return com.weimob.mcloud.wechatwork.core.base.MultiResponse<com.weimob.mcloud.wechatwork.core.entity.relation.employee.Employee>
     * @Author LeoLee
     * @Date 14:08 2022/8/23
     */
    public MultiResponse<Employee> fetchEmployee(PrivateSphere privateSphere, Integer pageSize, Integer pageNum) {
        SingleEmployeeAttachRequest<Employee> request = new SingleEmployeeAttachRequest<>();
        request.setPrivateSphere(privateSphere);
        request.setNeedPage(true);
        request.setPageSize(pageSize);
        request.setPageNum(pageNum);
        return SoaUtil.unpack(employeeService.fetchEmployee(request));
    }

    /**
     * 根据员工Ids获取员工列表
     *
     * @param employeeIds   employeeIds
     * @param privateSphere 私域
     * @return MultiResponse<Employee>
     */
    public MultiResponse<Employee> getByEmployeeIdOrTxUserIds(PrivateSphere privateSphere, List<String> employeeIds, List<String> userIds) {
        return getByEmployeeIdOrTxUserIds(privateSphere, employeeIds, userIds, false, false);
    }

    public MultiResponse<Employee> getByEmployeeIdOrTxUserIds(PrivateSphere privateSphere, List<String> employeeIds, List<String> userIds, boolean needDisplayName, boolean fetchGuider) {
        if (CollectionUtils.isEmpty(employeeIds) && CollectionUtils.isEmpty(userIds)) {
            return null;
        }
        SingleEmployeeAttachRequest<Employee> employeeRequest = new SingleEmployeeAttachRequest<>();
        Employee employee = new Employee();
        employee.setPrivateSphere(privateSphere);
        employeeRequest.setData(employee);
        employeeRequest.setIds(employeeIds);
        employeeRequest.setTxUserId(userIds);

        employeeRequest.setPrivateSphere(privateSphere);
        employeeRequest.setNeedDisplayName(needDisplayName);
        employeeRequest.setFetchGuider(needDisplayName);
        try {
            return SoaUtil.unpack(employeeService.fetchEmployee(employeeRequest));
        }catch (Exception e){
            log.error("fetchEmployee 接口异常:{}", JSON.toJSONString(employeeRequest),e);
            return new MultiResponse<>(new ArrayList<>());
        }
    }

    /**
     * 根据群成员获取员工信息
     *
     * @param privateSphere privateSphere
     * @param memberList    memberList
     * @return List<Employee>
     */
    public List<Employee> getEmployeeByGroupMemberList(PrivateSphere privateSphere, List<CustomerGroupMember> memberList) {
        Set<String> employeeIdSet = memberList.stream()
                .filter(m -> GroupMemberTypeEnum.EMPLOYEE.equals(m.getGroupMemberType()) && Objects.nonNull(m.getEmployee()) && Objects.nonNull(m.getEmployee().getId()))
                .map(m -> m.getEmployee().getId())
                .collect(Collectors.toSet());

        List<Future<List<Employee>>> employeeFutureList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(employeeIdSet)) {
            List<List<String>> partition = Lists.partition(new ArrayList<>(employeeIdSet), partitionSize);
            for (List<String> list : partition) {
                Future<List<Employee>> future = commonThreadPool.submit(() -> {
                    // 查询员工
                    MultiResponse<Employee> multiResponse = getByEmployeeIdOrTxUserIds(privateSphere, list, null);
                    if (Objects.isNull(multiResponse)) {
                        return new ArrayList<>();
                    }
                    return multiResponse.getDataList();
                });
                employeeFutureList.add(future);
            }
        }

        List<Employee> allEmployee = new ArrayList<>();
        if (!CollectionUtils.isEmpty(employeeFutureList)) {
            for (Future<List<Employee>> future : employeeFutureList) {
                try {
                    List<Employee> employees = future.get(2L, TimeUnit.SECONDS);
                    if (CollectionUtils.isEmpty(employees)) {
                        continue;
                    }
                    allEmployee.addAll(employees);
                } catch (Exception e) {
                    log.error("getEmployeeByGroupMemberList,查询员工信息异常 error:", e);
                }
            }
        }
        return allEmployee;
    }

    /**
     * 根据userId或employeeId查询员工信息
     *
     * @param privateSphere
     * @param userId
     * @param employeeId
     * @return
     */
    public Employee fetchEmployeeById(PrivateSphere privateSphere, String userId, String employeeId) {
        return fetchEmployeeById(privateSphere, userId, employeeId, false, null);
    }

    public Employee fetchEmployeeById(PrivateSphere privateSphere, String userId, String employeeId,boolean fetchGuider) {
        return fetchEmployeeById(privateSphere, userId, employeeId, fetchGuider, null);
    }

    public Employee fetchEmployeeById(PrivateSphere privateSphere, String userId, String employeeId, boolean fetchGuider, Boolean deleted) {
        if (ObjectUtils.isEmpty(privateSphere)) {
            log.error("查询员工失败 because: privateSphere为空");
            return null;
        }
        if (StringUtils.isBlank(userId) && StringUtils.isBlank(employeeId)) {
            log.error("查询员工失败 because: userId&employeeId 都为空");
            return null;
        }
        try {
            SingleEmployeeAttachRequest<Employee> groupRequest = new SingleEmployeeAttachRequest<>();
            Employee employee = new Employee();
            employee.setPrivateSphere(privateSphere);
            employee.setTxUserId(userId);
            employee.setId(employeeId);
            employee.setDeleted(deleted);

            groupRequest.setData(employee);
            groupRequest.setFetchGuider(fetchGuider);
            groupRequest.setPrivateSphere(privateSphere);
            MultiResponse<Employee> employeeMultiResponse = SoaUtil.unpack(employeeService.fetchEmployee(groupRequest));
            if (Objects.isNull(employeeMultiResponse) || org.apache.commons.collections.CollectionUtils.isEmpty(employeeMultiResponse.getDataList())) {
                return null;
            }
            return employeeMultiResponse.getDataList().get(0);
        } catch (Exception e) {
            log.error("查询员工失败 error: ", e);
            return null;
        }
    }


}
